package online.afeibaili.storebackendframework.controller

import online.afeibaili.storebackendframework.model.*
import online.afeibaili.storebackendframework.model.json.CouponJsonMapper
import online.afeibaili.storebackendframework.model.json.ProductJsonMapper
import online.afeibaili.storebackendframework.service.impl.*
import online.afeibaili.storebackendframework.util.*
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController


/**
 * 用户接口
 *
 *@author AfeiBaili
 *@version 2025/10/21 14:06
 */

@RestController
@RequestMapping("/user")
class UserController {

    @Autowired
    private lateinit var accountServiceImpl: AccountServiceImpl

    @Autowired
    lateinit var productServiceImpl: ProductServiceImpl

    @Autowired
    lateinit var orderServiceImpl: OrderServiceImpl

    @Autowired
    lateinit var shoppingCartServiceImpl: ShoppingCartServiceImpl

    @Autowired
    lateinit var addressServiceImpl: AddressServiceImpl

    /**
     * ## 向购物车添加商品
     *
     * @param accountId 账户id
     * @param productId 商品id
     * @param productCount 商品数量
     * @return 如果账户id或商品id不存在返回400
     */
    @PostMapping("/cart/add/product")
    fun addProductToCart(
        @RequestParam accountId: String,
        @RequestParam productId: Long,
        @RequestParam productCount: Int,
    ): Response {
        val pair: Pair<AccountEntity, ProductEntity>? =
            shoppingCartServiceImpl.addProduct(accountId, ProductJsonMapper(productId, productCount))

        if (pair != null) {
            return ok(200, pair)
        }
        return ok(400, "用户id或产品id未知")
    }

    /**
     * ## 向购物车删除商品
     *
     * @param accountId 账户id
     * @param productId 商品id
     * @param productCount 要删除商品数量
     * @return 如果账户id或商品id不存在返回400
     */
    @PostMapping("/cart/remove/product")
    fun deleteProductToCart(
        @RequestParam accountId: String,
        @RequestParam productId: Long,
        @RequestParam productCount: Int,
    ): Response {
        val pair: Pair<AccountEntity, ProductEntity>? =
            shoppingCartServiceImpl.deleteProduct(accountId, ProductJsonMapper(productId, productCount))
        if (pair != null) {
            return ok(200, pair)
        }
        return ok(400, "用户id或产品id不存在")
    }

    /**
     * ## 清空购物车
     *
     * @param accountId 账户id
     *
     * @return 如果账户不存在返回400
     */
    @PostMapping("/cart/clear")
    fun clearProductToCart(@RequestParam accountId: String): Response {
        val products: Boolean = shoppingCartServiceImpl.clearProducts(accountId)
        return if (products) ok(200, "删除成功")
        else ok(400, "删除失败，账户id或购物车id不存在")
    }

    /**
     * ## 获取当前用户购物车所有物品
     *
     * @param accountId 账户id
     * @return 返回当前购物车的列表
     */
    @PostMapping("/cart/item/get")
    fun getAllCartItem(@RequestParam accountId: String): Response {
        val products: List<ProductEntity> = shoppingCartServiceImpl.getProducts(accountId)
        return ok(200, products)
    }

    /**
     * ## 获取或创建一个用户的购物车
     *
     * @param accountId 账户id
     * @return 如果账户不存在返回400
     */
    @PostMapping("/cart/get")
    fun getOrCreateCart(@RequestParam accountId: String): Response {
        val entity: ShoppingCartEntity? = shoppingCartServiceImpl.getOrCreate(accountId)
        return if (entity != null) ok(200, entity)
        else ok(400, "未知的id")

    }

    /**
     * ## 获取当前账户的所有订单
     *
     * @param accountId 账户id
     * @return 返回订单列表
     */
    @PostMapping("/orders/get")
    fun getOrders(@RequestParam accountId: String): Response {
        val orders: List<OrderEntity> = orderServiceImpl.getOrders(accountId)
        return ok(200, orders)
    }

    /**
     * ## 获取当前用户所有的优惠券
     *
     * @param accountId 账户id
     * @return 如果id不存在返回400
     */
    @PostMapping("/coupons/get")
    fun getCoupons(@RequestParam accountId: String): Response {
        val coupons: List<CouponJsonMapper>? = accountServiceImpl.getCouponsJsonMapper(accountId)
        if (coupons == null) return ok(400, "找不到用户id")
        return ok(200, coupons)
    }

    /**
     * ## 创建一个空订单（只包含产品）
     *
     * @param accountId 用户id
     * @param products 产品数组
     *
     * @return 返回订单Id
     */
    @PostMapping("/order/create")
    fun createOrder(
        @RequestParam accountId: String,
        @RequestParam products: String,
    ) = response {
        val entity = OrderEntity(accountId, products)
        val createEntity: OrderEntity = orderServiceImpl.create(entity)

        data class Id(val orderId: String)
        200 data Id(createEntity.createTime.toString())
    }

    /**
     * ## 根据订单id获取订单信息
     *
     * @param accountId 用户id
     * @param orderId 订单id
     *
     * @return 返回订单信息
     * - 如果找不到用户返回400
     * - 如果找不到订单返回401
     */
    @PostMapping("/order/get")
    fun getOrderProduct(accountId: String, orderId: Long) = response {
        val accountEntity: AccountEntity? = accountServiceImpl.getById(accountId)
        if (accountEntity == null) return@response 400 message "找不到用户"
        val entity: OrderEntity? = orderServiceImpl.getById(orderId)
        if (entity == null) return@response 401 message "找不到订单"
        200 data entity
    }

    /**
     * ## 支付订单
     *
     * @param orderId 订单id
     * @return 如果找不到订单
     */
    @PostMapping("/order/pay")
    fun payOrder(@RequestParam orderId: Long): Response {
        val entity: OrderEntity? = orderServiceImpl.updatePaymentTime(orderId, System.currentTimeMillis())
        return if (entity != null) ok(200, entity)
        else ok(400, "找不到订单")
    }

    /**
     * ## 完成订单
     *
     * @param orderId 订单id
     * @return 如果找不到订单
     */
    @PostMapping("/order/complete")
    fun completeOrder(@RequestParam orderId: Long): Response {
        val entity: OrderEntity? = orderServiceImpl.updatePaymentTime(orderId, System.currentTimeMillis())
        return if (entity != null) ok(200, entity)
        else ok(400, "找不到订单")
    }

    /**
     * ## 保存收货地址
     *
     * @param accountId 用户id
     * @param name 收货人姓名
     * @param tel 电话
     * @param province 省
     * @param city 市
     * @param county 县
     * @param detail 详细地址
     *
     * @return 返回收货地址
     */
    @PostMapping("/address/save")
    fun saveAddress(
        @RequestParam accountId: String,
        @RequestParam name: String,
        @RequestParam tel: String,
        @RequestParam province: String,
        @RequestParam city: String,
        @RequestParam county: String,
        @RequestParam detail: String,
    ) = response {
        200 data addressServiceImpl.save(AddressEntity(accountId, name, tel, province, city, county, detail))
    }

    /**
     *  ## 根据地址（用户）id获取收货地址
     *
     *  @param accountId 用户id
     *
     *  @return 返回收货地址
     *  - 如果id不存在返回400
     */
    @PostMapping("/address/get/id")
    fun getAddressById(
        @RequestParam accountId: String,
    ) = response {
        val entity: AddressEntity? = addressServiceImpl.getById(accountId)
        if (entity == null) return@response 400 message "id不存在"
        200 data entity
    }
}